package com.yzc.android.network.base;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.yzc.android.utils.LogUtils;

/**
 * Created by yzc on 16/1/28.
 */
public class KDGsonRequest<T> extends KDBaseRequest<T> {

    protected final Class<T> clazz;

    public KDGsonRequest(int method,
                         Class<T> clazz,
                         Map<String, String> params,
                         Response.Listener<T> listener,
                         Response.ErrorListener errorListener) {
        super(method, null, params, listener, errorListener);
        this.clazz = clazz;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));

            T result;
            try {
                result = gson.fromJson(json, clazz);
            }
            catch(Exception ex){
                Type clazzListType = new TypeToken<List<T>>() {}.getType();
                result = gson.fromJson(json, clazzListType);
            }
            Response<T> jsonResponse = Response.success(result, HttpHeaderParser.parseCacheHeaders(response));

            try {
                String paramJson = gson.toJson(getParams());
                LogUtils.t(loggerTag).d("method=%s%nparams=%s%nresponse=%s", getUrl(), paramJson, gson.toJson(jsonResponse.result));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return jsonResponse;
        } catch (UnsupportedEncodingException e) {
            LogUtils.e(loggerTag, e, "UnsupportedEncodingException");
            e.printStackTrace();
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            LogUtils.e(loggerTag, e, "JsonSyntaxException");
            e.printStackTrace();
            return Response.error(new ParseError(e));
        }
    }
}
